package com.example.runningman.user;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import android.content.Intent;
import android.nfc.tech.NfcBarcode;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.runningman.MainActivity;
import com.example.runningman.R;
import com.example.runningman.adapter.Art_adapter;
import com.example.runningman.bean.Art;
import com.example.runningman.bean.User;
import com.example.runningman.util.SPUtil;
import com.example.runningman.util.TextUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.sql.BatchUpdateException;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

public class RegisterActivity extends AppCompatActivity{
    private EditText name;
    private EditText pwd;
    private EditText repwd;
    UUID uuid;
    private EditText phonenu;
    private EditText codenu;
    private String name1,pwd1;
    private Button reg;
    private String code;
    private static Gson gson=new Gson();
    private Mhandler mHandler;
    Button regs;
    final OkHttpClient client = new OkHttpClient();
    private class Mhandler extends Handler{
        private WeakReference<RegisterActivity> mActivity;
        private String code;

        public Mhandler(RegisterActivity activity){
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==2){
                String ReturnMessage = (String) msg.obj;
                Log.i("获取的返回信息",ReturnMessage);
                if(ReturnMessage=="用户已存在"||"用户已存在".equals(ReturnMessage)){
                    Toast.makeText(RegisterActivity.this, "电话已注册",Toast.LENGTH_SHORT).show();

                }else {
                    code=ReturnMessage;
                    SPUtil.getInstance(getApplicationContext()).putString("code", code);
                }

                /***
                 * 在此处可以通过获取到的Msg值来判断
                 * 给出用户提示注册成功 与否，以及判断是否用户名已经存在
                 */

            }
            if(msg.what==1){
                String ReturnMessage = (String) msg.obj;
                Log.i("获取的返回信息",ReturnMessage);
                if(ReturnMessage=="1"||"1".equals(ReturnMessage)){

                    SPUtil.getInstance(getApplicationContext()).putString("username",name.getText().toString());
                    SPUtil.getInstance(getApplicationContext()).putString("phone",phonenu.getText().toString());
                    SPUtil.getInstance(getApplicationContext()).putString("useid",uuid.toString());
                    Toast.makeText(RegisterActivity.this, "注册成功",Toast.LENGTH_SHORT).show();
                    finish();
                    Intent intent;
                    intent = new Intent(RegisterActivity.this, MainActivity.class);
                    startActivity(intent);
                }
            }
            if(msg.what==111){
                reg.setEnabled(true);
                reg.setBackgroundResource(R.color.btn);
                reg.setText("发获取验证码");
            }
            if(msg.what==222){

                reg.setText("("+msg.obj+")秒后重新获取验证码");
            }
        }
    }





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
/**
 * 初始化
 */
        name=findViewById(R.id.reg_username);
        pwd=findViewById(R.id.reg_password);
        repwd=findViewById(R.id.reg_repassword);
        phonenu=findViewById(R.id.phoneNumber);
        codenu=findViewById(R.id.yanZhengMaText);
        mHandler = new Mhandler(this);
        reg=findViewById(R.id.reg);
        regs=findViewById(R.id.queRenZhuCeBtn);
        reg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取相关参数
//                name1=name.getText().toString().trim();
//                pwd1=pwd.getText().toString().trim();
                if("".equals(phonenu.getText().toString())){
                    Toast.makeText(getApplicationContext(),"输入手机号码",Toast.LENGTH_SHORT).show();
                }else{
                    if(TextUtil.isPhoneNum(phonenu.getText().toString())){
                        postRequestCode(phonenu.getText().toString());
                        reg.setEnabled(false);
                        reg.setBackgroundResource(R.color.darkgrey);
                        timerTest();
                    }else{
                        Toast.makeText(getApplicationContext(),"输入正确的手机号码",Toast.LENGTH_SHORT).show();
                    }

                }

            }
        });
        regs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if("".equals(name.getText().toString())||"".equals(phonenu.getText().toString())||"".equals(codenu.getText().toString())||"".equals(pwd.getText().toString())||"".equals(repwd.getText().toString())){
                    Toast.makeText(getApplicationContext(),"输入完整信息",Toast.LENGTH_SHORT).show();
                }else{
                    if(repwd.getText().toString().equals(pwd.getText().toString())){
                        code=SPUtil.getInstance(getApplicationContext()).getString("code","ssdasd");
                        if(TextUtil.isContainLettersAndNumbers(pwd.getText().toString())){
                            if(TextUtil.isUserName(name.getText().toString())){
                                if(code.equals(codenu.getText().toString())){
                                    User user=new User();
                                    uuid = UUID.randomUUID();
                                    user.setUuid(uuid.toString());
                                    user.setUsername(name.getText().toString());
                                    user.setPassword(pwd.getText().toString());
                                    user.setPhone(phonenu.getText().toString());
                                    Date date=new Date(System.currentTimeMillis());
                                    user.setCreatedate(date.toString());
                                    String s= gson.toJson(user);
                                    //通过okhttp发起post请求
                                    Log.e("ddd", s);
                                    postRequest(s);

                                }else{
                                    Toast.makeText(getApplicationContext(),"输入正确的验证码",Toast.LENGTH_SHORT).show();
                                }
                            }else {
                                Toast.makeText(getApplicationContext(),"用户名只能由数字、字母、汉字组成",Toast.LENGTH_SHORT).show();
                            }
                        }else {
                            Toast.makeText(getApplicationContext(),"密码只能由数字、字母组成",Toast.LENGTH_SHORT).show();
                        }



                    }
                    else{
                        Toast.makeText(getApplicationContext(),"输入相同的密码",Toast.LENGTH_SHORT).show();
                    }
                }

            }
        });

    }
    int i=60;
    Timer timer;
    public  void timerTest(){
        //创建一个定时器
        timer = new Timer();

        //schedule方法是执行时间定时任务的方法
        timer.schedule(new TimerTask() {

            //run方法就是具体需要定时执行的任务
            @Override
            public void run() {
                if(i==0){
                    mHandler.obtainMessage(111).sendToTarget();
                }else {
                    i--;
                    mHandler.obtainMessage(222,i).sendToTarget();

                }

            }
        }, 200,1000);

    }
    /**
     * post请求后台
     * @param user
     */
    private void postRequest(String user)  {
        //建立请求表单，添加上传服务器的参数
        RequestBody formBody = new FormBody.Builder()
                .add("user",user)
                .build();
        //发起请求
        final Request request = new Request.Builder()
                .url("http://120.26.177.58:8080/AndroidServer01/addUser?")
                .post(formBody)
                .build();
        //新建一个线程，用于得到服务器响应的参数
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        mHandler.obtainMessage(1, response.body().string()).sendToTarget();

                    } else {
                        throw new IOException("Unexpected code:" + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
    private void postRequestCode(String phone)  {
        //建立请求表单，添加上传服务器的参数
        RequestBody formBody = new FormBody.Builder()
                .add("phone",phone)
                .build();
        //发起请求
        final Request request = new Request.Builder()
                .url("http://120.26.177.58:8080/AndroidServer01/sendCode?")
                .post(formBody)
                .build();
        //新建一个线程，用于得到服务器响应的参数
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        mHandler.obtainMessage(2, response.body().string()).sendToTarget();

                    } else {
                        throw new IOException("Unexpected code:" + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}

